<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\WechatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class AuthController extends Controller
{
    /**
     * 小程序登录
     */
    public function login(Request $request)
    {
        $request->validate([
            'code' => 'required|string'
        ]);
        
        $code = $request->input('code');
        
        try {
            // 调用微信接口获取openid和session_key
            $wechatService = app(WechatService::class);
            $sessionInfo = $wechatService->code2Session($code);
            Log::error($sessionInfo);
            // 查找或创建用户
            $user = User::firstOrCreate(
                ['open_id' => $sessionInfo['openid']],
                [
                    'session_key' => $sessionInfo['session_key'],
                    'is_active' => true,
                    'password' => bcrypt(Str::random(16))
                ]
            );
            
            // 生成令牌
            $token = $user->createToken('auth_token')->plainTextToken;
            
            return response()->json([
                'status' => 'success',
                'user' => [
                    'id' => $user->id,
                    'nickname' => $user->nickname,
                    'avatar_url' => $user->avatar_url,
                ],
                'token' => $token,
                'is_new_user' => $user->wasRecentlyCreated
            ]);
        } catch (\Exception $e) {
            Log::error('登录失败', ['error' => $e->getMessage()]);
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage()
            ], 401);
        }
    }
    
    /**
     * 更新用户信息
     */
    public function updateUserInfo(Request $request)
    {
        $request->validate([
            'nickname' => 'required|string|max:100',
            'avatar_url' => 'required|string|max:255'
        ]);
        
        $user = \App\Models\User::find(auth()->id());
        if (!$user) {
            return response()->json([
                'status' => 'error',
                'message' => '用户未找到'
            ], 404);
        }
        
        // 手动更新字段
        $user->nickname = $request->nickname;
        $user->avatar_url = $request->avatar_url;
        $user->save();
        
        return response()->json([
            'status' => 'success',
            'user' => [
                'id' => $user->id,
                'nickname' => $user->nickname,
                'avatar_url' => $user->avatar_url,
            ]
        ]);
    }
    
    /**
     * 获取用户信息
     */
    public function getUserProfile()
    {
        $user = auth()->user();
        
        $data = [
            'id' => $user->id,
            'nickname' => $user->nickname,
            'avatar_url' => $user->avatar_url,
        ];
        
        // 检查是否有挪车码
        if ($user->carOwner) {
            $data['car_owner'] = [
                'phone_number' => $user->carOwner->phone_number,
                'qr_code_url' => $user->carOwner->qr_code_path ? url($user->carOwner->qr_code_path) : null,
            ];
        }
        
        return response()->json([
            'status' => 'success',
            'user' => $data
        ]);
    }
}
